<template>
	<div style="text-align: right;margin-bottom: 10px;"> 
		<el-button :icon="Tools" size='mini' circle @click="openConfigColumns=true" />
		<el-button :icon="FullScreen" size='mini' circle @click="viewFullScreen" />
		<el-button :icon="Download" size='mini' circle @click="xlsxDownload" /> 
		<el-button :icon="Printer" size='mini' circle @click="viewPrint" />
		<el-button :icon="Histogram" size='mini' circle @click="view='bar'" v-if="chartColumn.length>0&&dataColumn.length>0&&view=='table'" />
		<el-button :icon="Grid" size='mini' circle @click="view='table'" v-if="view!='table'" />
	</div>
	<el-drawer v-model="openConfigColumns" title="字段编辑" size="900px" >
	    <el-table :data="columns" border>
			<el-table-column :prop="edit.code" :width="edit.width" :label="edit.name" v-for="edit in configColumns" align="center">
				<template #default="scope">
					<template v-if="edit.type=='text'">
						<el-input v-model="scope.row[edit.code]"></el-input>
					</template>
					<template v-else-if="edit.type=='checkbox'">
					   <el-checkbox v-model="scope.row[edit.code]"  />
					</template>
					<template v-else-if="edit.type=='select'">
						<el-select v-model="scope.row[edit.code]" style="width: 100%;" :clearable="edit.clearable"  placeholder="请选择" >
						    <el-option v-for="item in edit.data" :key="item.code" :label="item.name" :value="item.code" />
						</el-select>
					</template>
					<template v-else>
						{{scope.row[edit.code]}}
					</template>
				</template>
			</el-table-column>
		</el-table>
	</el-drawer>
 
	<el-table v-bind="configTable" style="width: 100%" ref="table" v-if="view=='table'" v-on="configEvent" >
		<template v-for="item in columns">
			<el-table-column :prop="item.code" v-bind="item" v-if="item.show" :label="item.name" :width="item.width" >
				<template #header>
					<template v-if="item.headSloatName!=null">
						<slot :column="item"  ></slot>
					</template>
					<template v-else>
						{{item.name}}
					</template>
					<template v-if="item.filtersType">
						 <el-popover :width="200"  trigger="click" >
							<div>
								<template v-if="item.filtersType=='text'">
									<el-input v-model="queryDataModel[item.code]" />
								</template>
								<template v-else-if="item.filtersType=='select'">
									<div style="height: 400px;overflow-y: auto;">
										<el-checkbox-group v-model="queryDataModel[item.code]">
											<div v-for="item of dataColumnsMap[item.code]">
												<el-checkbox :label="item" />
											</div>
									  </el-checkbox-group>
									</div>
									<div style="margin-top: 5px;">
										<el-button @click="queryDataModel[item.code]=[]">重置</el-button>
									</div>
								</template>
							</div>
							<template #reference>
								<el-icon><Filter /></el-icon>
							 </template>
						   </el-popover>
					</template>
				</template>
				<template #default="scope">
					<template v-if="item.slotName!=null">
						<slot :name="item.slotName" :row="scope.row" :column="item"  ></slot>
					</template>
					<template v-else>
						{{scope.row[item.code]}}
					</template>
				</template>
		
			</el-table-column>
		</template>
	</el-table>
	<div v-else> 
		<el-row>
			<el-col :span="12">
				<div style="text-align: left;">
					<el-tag  :effect="item==mainChartColumnValue?'dark':'plain'" effect="dark" style="margin-right: 10px;cursor: pointer;" v-for="item in chartColumn" @click="setMainChartColumn(item)">
					  {{item.name}} 
					</el-tag>
				</div>
			</el-col>
			<el-col :span="12">
				<div style="text-align: right;">
					<template v-for="item in dataColumn" >
						 <el-dropdown>
						   <el-tag effect="plain"  style="margin-left: 10px;cursor: pointer;" >
						   	{{item.name}}({{
								item.dataEchartType=='max'?'最大':
								item.dataEchartType=='min'?'最小':
								item.dataEchartType=='count'?'次数':
								item.dataEchartType=='avg'?'平均':
								item.dataEchartType=='sum'?'汇总':''
								}})
						   </el-tag>
						    <template #dropdown>
						      <el-dropdown-menu>
						        <el-dropdown-item @click="item.dataEchartType='max'" >最大</el-dropdown-item>
						        <el-dropdown-item @click="item.dataEchartType='min'">最小</el-dropdown-item>
						        <el-dropdown-item @click="item.dataEchartType='count'">次数</el-dropdown-item>
								<el-dropdown-item @click="item.dataEchartType='avg'">平均</el-dropdown-item>
								<el-dropdown-item @click="item.dataEchartType='sum'">汇总</el-dropdown-item>
						      </el-dropdown-menu>
						    </template>
						  </el-dropdown>
						
					</template>
					 
				</div>
				
			</el-col>
		</el-row> 
		<v-echarts :option="echartsOption"></v-echarts>
	</div>
	 
</template>

<script setup>
 
	import {Tools,FullScreen,Download,Printer,Histogram,Grid} from '@element-plus/icons-vue';
	import { computed,ref,watch } from 'vue'; 
	import FileSaver from 'file-saver';
	import * as XLSX from 'xlsx';
	import screenfull  from 'screenfull';  
	import vEcharts from './vEcharts.vue'
	const view=ref('table');
	const mainChartColumn=ref(null);
	const openConfigColumns=ref(false);
	const table=ref(null);
	const queryDataModel=ref({});
	const printDom=ref(null);
	const viewPrint=()=>{  
		var headhtml=table.value.$el.getElementsByClassName("el-table__header")[0].getElementsByTagName("thead")[0].innerHTML;
		var bodyhtml=table.value.$el.getElementsByClassName("el-table__body")[0].getElementsByTagName("tbody")[0].innerHTML; 
		var iframe=document.createElement("iframe");
		iframe.style.display="none";
		document.body.append(iframe); 
		iframe.contentWindow.document.getElementsByTagName("body")[0].innerHTML=`
				<table style='width:100%'>
					<thead>
					${headhtml}
					</thead>
					<tbody>
					${bodyhtml}
					</tbody>
				</table>
		` 
		iframe.contentWindow.print();
		iframe.remove();
	}
	const setMainChartColumn=(item)=>{
		mainChartColumn.value=item; 
	}
	const xlsxDownload=()=>{
		var wb = XLSX.utils.table_to_book(table.value.$el);
		var wbout = XLSX.write(wb, { bookType: 'xlsx', bookSST: true, type: 'array' })
		try {
			 FileSaver.saveAs(new Blob([wbout], { type: 'application/octet-stream' }), 'sheetjs.xlsx')
		} catch (e) { 
			if (typeof console !== 'undefined') console.log(e, wbout) 
		}
		return wbout;
	}
	const viewFullScreen=()=>{
		screenfull.toggle(table.value.$el); 
	}
	const configColumns=[
		{code:"code",name:"字段编码",width:"90px"},
		{code:"name",name:"字段名称",type:"text"},
		{code:"show",name:"是否显示",type:"checkbox"},
		{code:"sortable",name:"是否排序",type:"checkbox"},
		{
			code:"filtersType",
			name:"搜索方式",
			type:"select",
			clearable:true,
			data:[
				{code:"text",name:"文本"},
				{code:"select",name:"下拉框"},
			]
		},
		{
			code:"align",
			name:"对齐方式",
			type:"select",
			clearable:true,
			data:[
				{code:"left",name:"左边"},
				{code:"center",name:"中间"},
				{code:"right",name:"右边"}
			],
		},
		{
			code:"fixed",
			name:"停靠方式",
			type:"select",
			clearable:true,
			data:[
				{code:"left",name:"左边"},
				{code:"right",name:"右边"}
			],
		}
	]
	const props = defineProps({
		data: Array,
		columns:Array,
		configTable:Object,
		configEvent:Object
	}); 
	const mainChartColumnValue = computed(() => {
		if(chartColumn.value.length>0){
			if(mainChartColumn.value){
				return mainChartColumn.value;
			}else{
				return chartColumn.value[0];
			}
		}else{
			mainChartColumn.value;
		}
	});
	const columns = computed(() => {
		return props.columns;
	});
	const chartColumn = computed(() => {
		return props.columns.filter(item=>item.dataType=='column');
	});
	const dataColumn = computed(() => {
		return props.columns.filter(item=>item.dataType=='number');
	});
	const echartsData=computed(() => {
		if(mainChartColumnValue.value){
			var data= props.data;
			var columnMain=mainChartColumnValue.value; 
			var groupData=data.reduce((item1,item2)=>{
				var value=item2[columnMain.code];
				if(!item1[value]){
					item1[value]=[]
				}
				item1[value].push(item2);
				return item1;
			},{}); 
			return groupData;
		}else{
			return {};
		}
	});
	
	const echartsDataHandling=function(data,column){
		if(column.dataEchartType=='sum'){
			var sum=data.reduce((value,item)=>{
				value+=(item[column.code]?item[column.code]:0);
				return value;
			},0); 
			return sum.toFixed(2)-0;
		}else if(column.dataEchartType=='count'){
			return data.length;
		}else if(column.dataEchartType=='max'){
			return Math.max.apply(null, data.map(item => item[column.code]));
		}else if(column.dataEchartType=='min'){
			return Math.min.apply(null, data.map(item => item[column.code]));
		}else if(column.dataEchartType=='avg'){
			var sum=data.reduce((value,item)=>{
				value+=(item[column.code]?item[column.code]:0);
				return value;
			},0); 
			return (sum/data.length).toFixed(2)-0;
		}
	}
	const echartsOption=computed(() => { 
		var data=echartsData.value;
		var xAxis=[];
		var legend=dataColumn.value.map(item=>item.name);
		for(var name in data){
			xAxis.push(name);  
		}
		var series=[]; 
		for(var dataItem of dataColumn.value){
			var charData=[];
			for(var name of xAxis){
				charData.push(echartsDataHandling(data[name],dataItem)); 
			}
			series.push({
				name:dataItem.name,
				type: 'line', 
				data:charData
			})
		} 
		return {
			tooltip: {
				trigger: 'axis'
			},
			grid: {
			    left: '3%',
			    right: '4%',
			    bottom: '3%',
			    containLabel: true
			},
			yAxis: {},
			legend: {
				data:legend
			},
			xAxis: {
				data: xAxis
			}, 
			series: series
		};
	});
	const data = computed(() => {
		var data= props.data;
		var filtersData=columns.value.filter(item=>item.filtersType);
		for(var filters of filtersData){
			var value=queryDataModel.value[filters.code];
			if(value&&value.length>0){
				if(filters.filtersType=='text'){
					//文本框搜索
					data=data.filter(item=>item[filters.code]&&item[filters.code].indexOf(value)!=-1);
				}else if(filters.filtersType=='select'){
					//数组搜索		["123","aaa","sdfsdf"].indexOf("123");
					data=data.filter(item=>item[filters.code]&&value.indexOf(item[filters.code])!=-1);
				}
			}
		}
		return data;
	});
	const configTable = computed(() => {
		return {
			...props.configTable,
			data:data.value
		}
	});
	const dataColumnsMap=computed(() => {
		var data= props.data;
		var selectData=props.columns.filter(item=>item.filtersType=='select');
		var map={};
		for(var row of data){
			for(var columns of selectData){
				if(!map[columns.code]){
					map[columns.code]={};
				}
				if(row[columns.code]){
					map[columns.code][row[columns.code]]=true;
				}
			}
		}
		for(var name in map){
			map[name]=Object.keys(map[name]);
		}
		return map;
		
	});
	/**
	 * 初始化字段类型
	 * 	show字段初始化
	 * 	dataType如果为number
	 * 		判断是否有dataEchartType字段 
	 * 	dataEchartType 默认有类型 sum avg count max min 几大类型
	 */
	watch(props.columns,(data)=>{
		if(data){
			for(var item of data){
				if(!item.hasOwnProperty("show")){
					item.show=true;
				}
				if(item.dataType=="number"){	
					if(!item.hasOwnProperty("dataEchartType")){
						item.dataEchartType='sum';
					}
				}
			}
		}
	},{
		immediate:true,
		deep:true
	})
</script>
<style>
</style>